import { AppContext } from "../app.context";
import {
  NetStatusCode,
  RespResultCode,
  StatusResp,
  WXResp,
  ErrorInfo,
} from "./parameters"
const config = require("./config").config;


export class BaseServices {
  constructor() { }

  protected checkResp(data: StatusResp): boolean {
    if (data.code !== undefined && data.code !== RespResultCode.Success) {
      // wx.reLaunch({
      //   url: '/pages/mine/login/login'
      // })
      wx.showToast({ title: data.message, icon: 'none', duration: 2000 })
      return false;
    }
    return true;
  }
  public returnImmediately(): Promise<void> {
    return new Promise<void>(resolve => {
      resolve();
    });
  }
  public request<T>(url: string, data: Object): Promise<T> {
    const header = AppContext.instance.getHeader();
    const that = this;
    return new Promise<T>((resolve, reject) => {
      let error: ErrorInfo;
      wx.request({
        url: config.httpHost + url,
        method: "POST",
        data,
        header,
        success: function (res: WXResp) {
          if (that.checkResp(res.data)) {
            resolve(res.data as T);
          } else {
            reject(error);
          }
        },
        fail: function (err) {
          error = {
            status: NetStatusCode.Error,
            errMsg: err.errMsg,
            code: 1
          }
          if (err.errMsg === ('request:fail timeout' || 'request:fail')) {
            wx.showToast({ title: '请求超时，请稍后重试', icon: 'none', duration: 3000 })
          } else {
            wx.showToast({ title: '网络无连接,请检查网络连接', icon: 'none' })
          }
          reject(error);
        },
        complete: function (info) {
          console.log('complete>>>:', config.httpHost + url, info);
        }
      });
    });
  }
}
